import requests,json,os,time,re

def clear_screen():
    os.system('cls' if os.name == 'nt' else 'clear')
def print_b(data, color=34):
    if isinstance(color ,int):
        color = str(color)
    return print(f'\033[1;{color}m{data}\033[0m')
def print_g(data, color=32):
    if isinstance(color, int):
        color = str(color)
    return print(f"\033[1;{color}m{data}\033[0m")
def print_r(data, color=31):
    if isinstance(color, int):
        color = str(color)
    return print(f"\033[1;{color}m{data}\033[0m")

def input_g(data, color=32):
    if isinstance(color, int):
        color = str(color)
    return input(f"\033[1;{color}m{data}\033[0m")

def json_time():
    file_path = "msr.json"
    create_time = os.path.getctime(file_path)
    readable_time = time.ctime(create_time)
    return print(f"msr.json数据更新时间:{readable_time}")

def title():
    print_b(r'''
 ___________________________________________________________________________   
  __  __  ____   _____                            
 |  \/  |/ ___| |  ___|                           
 | |\/| |\___ \ | |_                              
 | |  | | ___) ||  _|____                         
 |_|  |_||____/ |_| |  _ \   ___ __      __ _ __  
                    | | | | / _ \\ \ /\ / /| '_ \ 
Author:Amiya        | |_| || (_) |\ V  V / | | | |
Vision:1.0          |____/  \___/  \_/\_/  |_| |_|
___________________________________________________________________________ ''')

def msr_json(url):
    clear_screen()
    title()
    file_name = "msr.json"
    if not os.path.exists(file_name):
        # 发送请求
        response = requests.get(url)
        # 检查请求是否成功
        if response.status_code == 200:
            # 获取 JSON 数据
            data = response.json()
            # 将 JSON 数据写入文件
            with open("msr.json", "w", encoding="utf-8") as file:
                json.dump(data, file, ensure_ascii=False, indent=4)
            print_g("JSON 数据已成功写入 msr.json 文件")
            time.sleep(1)
        else:
            print_r(f"请求失败，状态码：{response.status_code}")
            time.sleep(1)
            exit()
    else:
        # 发送请求
        response = requests.get(url)
        # 检查请求是否成功
        if response.status_code == 200:
            # 获取 JSON 数据
            data = response.json()
            # 将 JSON 数据写入文件
            with open("msr.json", "w", encoding="utf-8") as file:
                json.dump(data, file, ensure_ascii=False, indent=4)
        else:
            print_r(f"请求失败，状态码：{response.status_code}")
            print_g('将沿用以前json数据')
            time.sleep(1)
            pass

    clear_screen()
    title()

def make_music():
    if not os.path.exists('music'):
        os.makedirs('music')
    else:
        pass

def get_html_url(cid):
    html_url = f'https://monster-siren.hypergryph.com/music/{cid}'
    return html_url

def load_json_file(file_path):
    """从文件加载JSON数据"""
    with open(file_path, 'r', encoding='utf-8') as file:
        data = json.load(file)
    return data

def find_songs_by_name(song_name, songs_list):
    """根据歌曲名称查找相关歌曲"""
    found_songs = []
    for song in songs_list:
        if song_name.lower() in song["name"].lower():
            found_songs.append(song)
    return found_songs

def display_song_details(song):
    """打印歌曲的详细信息"""
    print_b(f"CID: {song['cid']}")
    print_b(f"名称: {song['name']}")
    print_b(f"作者: {', '.join(song['artists'])}")
    print_b(f"专辑CID: {song['albumCid']}")
    return song['cid'],song['name']

def get_message():
    # 加载JSON文件
    file_path = 'msr.json'
    data = load_json_file(file_path)
    songs_list = data["data"]["list"]
    # 用户输入
    user_input = input_g("请输入歌曲名称或名称中的几个字：")
    found_songs = find_songs_by_name(user_input, songs_list)
    # 输出结果
    if found_songs:
        print_g(f"找到与 '{user_input}' 相关的歌曲：")
        for index, song in enumerate(found_songs, start=1):
            print_b(f"[{index}] {song['name']} cid:{song['cid']}")
        # 用户选择
        choice = input_g("请输入编号选择歌曲：")
        clear_screen()
        title()
        if choice.isdigit() and 1 <= int(choice) <= len(found_songs):
            selected_song = found_songs[int(choice) - 1]
            cid,name = display_song_details(selected_song)
            return cid,name
        else:
            print_r("无效的选择")
            exit()
    else:
        print_r(f"未找到与 '{user_input}' 相关的歌曲")
        exit()

def get_path():
    save_path = input_g('请输入下载路径,默认为当前文件夹下的music文件夹:')
    if os.path.exists(save_path):
        # 根据操作系统判断路径结尾是否正确
        if os.name == 'nt':  # Windows 系统
            if not save_path.endswith('\\'):
                save_path += '\\'
        elif os.name == 'posix':  # Linux 系统
            if not save_path.endswith('/'):
                save_path += '/'
        else:
            print("路径不存在，已使用默认下载路径")
            save_path = ''  # 重置为默认路径
    else:
        save_path = 'music/'
    return save_path

def get_down_url(html_url):
    response = requests.get(html_url)
    if response.status_code == 200:
        html = response.text
        pattern = r'"sourceUrl":"([^"]+\.\w+)"'
        matchs = re.findall(pattern, html)
        encoded_string = matchs[0]
        print_b(f"下载地址(未解码):{encoded_string}")
        decoded_string = encoded_string.replace("\\\\", "/")
        decoded_string = decoded_string.replace("\\u002F", "/")
        print_b(f"下载地址(已解码):{decoded_string}")
        return decoded_string
    else:
        print_r(f"请求失败，状态码：{response.status_code}")
        exit()

def download_music(url, save_path):
    try:
        # 发送 GET 请求
        response = requests.get(url, stream=True)
        response.raise_for_status()  # 检查请求是否成功
        # 打开文件并写入
        print_g('下载中...')
        with open(save_path, 'wb') as file:
            for chunk in response.iter_content(chunk_size=8192):  # 按块写入
                file.write(chunk)
        print_g(f"文件已成功下载并保存到 {save_path}")
    except requests.exceptions.RequestException as e:
        print_r(f"下载文件时发生错误: {e}")
        exit()

def main():
    make_music()
    url = "https://monster-siren.hypergryph.com/api/songs" 
    msr_json(url)
    save_path = get_path()
    cid,name = get_message()
    save_path = f'{save_path}{name}.mp3'
    html_url = get_html_url(cid)
    down_url = get_down_url(html_url)
    choose = input_g("是否进行下载(y/n):")
    if choose == str("y"):
        download_music(down_url, save_path)
        exit()
    else:
        print_g("已取消下载")
        exit()


if __name__ == '__main__':
    main()
    

